<template>
	<view class="workbench-detail">
		<!-- 事项明细标题 -->
		<view class="detail-title">{{ doWorkInfo.items }}</view>
		<!-- 明细概况 -->
		<view class="detail-content">
			<!-- <van-cell title="所属类型" value="售后部" icon="apps-o" /> -->
			<van-cell title="事项分类" :value="doWorkInfo.class" icon="points" />
			<van-cell title="执行标准" :value="doWorkInfo.standard" icon="guide-o" />
		</view>
		<!-- 是否完成 -->
		<view class="detail-iscompleted">
			<view class="detail-completed-form">
				<view class="detail-completed-title">
					<van-icon class="passed-icon" name="passed" />
					<text class="completed-title-text">完成状态</text>
				</view>
				<view class="detail-completed-radio-group">
					<uni-data-checkbox v-model="isCompleted" :localdata="completed" :disabled="isHistory" />
				</view>
			</view>
		</view>
		<!-- 点检痕迹 -->
		<view class="detail-tally-trace" v-if="!isHistory">
			<view class="detail-trace-title">执行痕迹</view>
			<view class="detail-tally-imgs">
				<view class="grid-item-box" v-for="(item, index) in imgs" :key="index"
					@tap.stop="ViewImage(item.imgName)">
					<image :src="item.imgName" class="tally-img" mode="aspectFill" />
					<van-icon class="delete-icon" name="clear" @tap.stop="DelImg(item.id, index)" />
				</view>
				<view class="grid-item-box detail-tally-img-add" v-show="isAddImgShow" @tap.stop="ChooseImage">
					<van-icon class="add-icon" name="plus" />
				</view>
			</view>
		</view>
		<!-- 点检痕迹 -->
		<view class="detail-tally-trace" v-else-if="isHistory && imgs.length > 0">
			<view class="detail-trace-title">执行痕迹</view>
			<view class="detail-tally-imgs">
				<view class="grid-item-box" v-for="(item, index) in imgs" :key="index"
					@tap.stop="ViewImage(item.imgName)">
					<image :src="item.imgName" class="tally-img" mode="aspectFill" />
				</view>
			</view>
		</view>

		<!-- 视频上传 -->
		<view class="detail-tally-trace" v-if="!isHistory">
			<view class="detail-trace-title">视频上传</view>
			<view class="detail-tally-imgs">
				<view class="grid-item-box" v-for="(item, index) in videos" :key="index">
					<image :src="item.cover" class="tally-img" mode="aspectFill" />
					<view class="play-icon-bg" @tap.stop.prevent="playVideo(item)">
						<van-icon class="play-icon" name="play-circle-o" />
					</view>
					<van-icon class="delete-icon" name="clear" @tap.stop="DelVideo(index)" />
				</view>
				<view class="grid-item-box detail-tally-img-add" v-show="isAddVideoShow" @tap.stop="ChooseVideo">
					<van-icon class="add-icon" name="plus" />
				</view>
			</view>
		</view>

		<!-- 视频上传 -->
		<view class="detail-tally-trace" v-else-if="isHistory && videos.length > 0">
			<view class="detail-trace-title">视频上传</view>
			<view class="detail-tally-imgs">
				<view class="grid-item-box" v-for="(item, index) in videos" :key="index">
					<image :src="item.cover" class="tally-img" mode="aspectFill" />
					<view class="play-icon-bg" @tap.stop.prevent="playVideo(item)">
						<van-icon class="play-icon" name="play-circle-o" />
					</view>
				</view>
			</view>
		</view>

		<!-- 备注 -->
		<view class="detail-tally-trace" v-if="!isHistory && isCompleted == 0">
			<view class="detail-trace-title">备注</view>
			<view class="detail-remark isNotHistory">
				<uni-easyinput type="textarea" :trim="true" :inputBorder="false" v-model="remark" placeholder="请输入备注" />
			</view>
		</view>

		<!-- 备注 -->
		<view class="detail-tally-trace" v-else-if="isCompleted == 0 && isHistory && remark.length > 0">
			<view class="detail-trace-title">备注</view>
			<view class="detail-remark isHistoryRemark">
				<uni-easyinput type="textarea" :disabled="isHistory" :trim="true" :inputBorder="false" v-model="remark"
					placeholder="请输入备注" />
			</view>
		</view>


		<!-- 是否完成popup -->
		<van-popup :show="completedPopShow" position="bottom">
			<van-picker show-toolbar :columns="completedList" @confirm="onCompletedConfirm"
				@cancel="completedPopShow = false" />
		</van-popup>

		<view v-if="isSubBtnShow">
			<button class="submit-btn" v-if="submitBtnState" @click.stop.prevent="handleSubmit">确认提交</button>
			<button class="unsubmit-btn" v-else>确认提交</button>
		</view>

		<view class="box-height" v-if="isSubBtnShow"></view>
	</view>
</template>

<script>
	import apiRqs from "@/api/api-request.js";
	export default {
		data() {
			return {
				remark: '',
				isCompleted: -1,
				completedPopShow: false,
				completedList: ['已完成', '未完成'],
				completed: [{
					text: '已完成',
					value: 1
				}, {
					text: '未完成',
					value: 0
				}],
				doWorkInfo: {},
				imgs: [],
				delImgs: [],
				shopId: '',
				isHistory: false,
				isAddImgShow: true,
				isSubBtnShow: false,
				videos: [],
				isAddVideoShow: true,
				submitBtnState: true,
			}
		},
		onShow() {

		},
		onLoad(option) {
			const doWorkInfo = uni.getStorageSync("doWorkCompletedInfo");
			if (doWorkInfo) {
				this.doWorkInfo = doWorkInfo;
				// this.imgs = doWorkInfo.imgs;
				for (let i = 0; i < doWorkInfo.imgs.length; i++) {
					let suffix = doWorkInfo.imgs[i].imgName.substring(doWorkInfo.imgs[i].imgName.length - 3, doWorkInfo
						.imgs[i].imgName.length);
					if (suffix == 'mp4') {
						this.isAddVideoShow = false;
						this.videos.push(doWorkInfo.imgs[i]);
					} else {
						this.imgs.push(doWorkInfo.imgs[i]);
					}
				}
				if (this.imgs.length < 9) {
					this.isAddImgShow = true;
				} else if (this.imgs.length == 9) {
					this.isAddImgShow = false;
				} else {
					this.isAddImgShow = false;
				}
				this.isCompleted = doWorkInfo.result;
				this.remark = doWorkInfo.remark;
			}
			const loginInfo = uni.getStorageSync("loginInfo");
			if (loginInfo && loginInfo.companys.length > 0) {
				this.shopId = loginInfo.companys[0].shopId;
			}
			if (option) {
				this.isHistory = option.isHistory;
				if (!option.isHistory) {
					this.isSubBtnShow = true;
				}
			}
		},
		methods: {
			handleCompletedPopShow() {
				this.completedPopShow = true;
			},
			onCompletedConfirm(value) {
				this.isCompleted = value.detail.value;
				this.completedPopShow = false;
			},
			// 上传图片
			ChooseImage(index) {
				let imgs = this.imgs;
				let loginInfo = uni.getStorageSync("loginInfo");
				var that = this;
				uni.chooseImage({
					count: 9, //默认最多上传6张图片
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], //从相册选择
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						// 将上传的图片分别请求上传到服务器
						if ((imgs.length + tempFilePaths.length) < 9) {
							that.isAddImgShow = true;
						} else if ((imgs.length + tempFilePaths.length) == 9) {
							that.isAddImgShow = false;
						} else {
							that.isAddImgShow = false;
						}
						for (let i = 0; i < tempFilePaths.length; i++) {
							uni.uploadFile({
								url: getApp().globalData.websiteUrl + "/api/v1/FileUpload",
								filePath: tempFilePaths[i],
								name: 'file',
								header: {
									'Authorization': ('Bearer ' + loginInfo.token) || ''
								},
								formData: {
									'fileType': 'CheckImg'
								},
								success: (uploadFileRes) => {
									let res = JSON.parse(uploadFileRes.data);
									let filePath = res.data[0].filePath;
									let newFilePath = filePath.replace(/\\/g, "/");
									let d = {
										id: "0",
										checkDetailId: "0",
										imgName: `${getApp().globalData.websiteUrl}${newFilePath}/${res.data[0].fileName}`,
										cover: "",
										width: res.data[0].width,
										height: res.data[0].height,
										softDelete: false
									}
									console.log('imgFileData', d);
									imgs.push(d);
								}
							});
						}
						that.imgs = imgs;
					}
				});
			},
			// 预览图片
			ViewImage(imgName) {
				console.log('点击了预览');
				let imgs = this.imgs;
				var dataArray = [];
				for (var i = 0; i < imgs.length; i++) {
					dataArray[i] = imgs[i].imgName;
				}
				uni.previewImage({
					urls: dataArray,
					current: imgName
				});
			},
			// 删除图片
			DelImg(id, index) {
				var that = this;
				that.delImgs.push(that.imgs[index]);
				that.imgs.splice(index, 1);
				if (that.imgs.length < 9) {
					that.isAddImgShow = true;
				} else if (that.imgs.length == 9) {
					that.isAddImgShow = false;
				} else {
					that.isAddImgShow = false;
				}
			},
			// 上传视频
			ChooseVideo() {
				let loginInfo = uni.getStorageSync("loginInfo");
				var that = this;
				uni.chooseMedia({
					count: 1,
					mediaType: ['video'],
					sourceType: ['camera', 'album'],
					maxDuration: 30,
					success: function(res) {
						let videoRes = res.tempFiles[0];
						let videoW = res.tempFiles[0].width;
						let videoH = res.tempFiles[0].height;
						if (videoRes.duration > 30) {
							getApp().showToast("视频时长不得大于30秒!");
							return false;
						} else if ((videoRes.size / 1024 / 1024) > 20) {
							getApp().showToast("视频大小不得大于20M!");
							return false;
						} else {
							getApp().showLoading();
							let thumbTempFilePath = videoRes.thumbTempFilePath;
							if (videoRes.tempFilePath) {
								let p1 = new Promise((resolve) => {
									uni.uploadFile({
										url: getApp().globalData.websiteUrl +
											"/api/v1/FileUpload",
										filePath: thumbTempFilePath,
										name: 'file',
										header: {
											'Authorization': ('Bearer ' + loginInfo.token) ||
												''
										},
										formData: {
											'fileType': 'CheckImg'
										},
										success: (uploadFileRes) => {

											let res = JSON.parse(uploadFileRes.data);
											let filePath = res.data[0].filePath;
											let newFilePath = filePath.replace(/\\/g, "/");
											let imgName =
												`${getApp().globalData.websiteUrl}${newFilePath}/${res.data[0].fileName}`;
											resolve(imgName);
										}
									});
								})
								p1.then((img) => {
									uni.uploadFile({
										url: getApp().globalData.websiteUrl +
											"/api/v1/FileUpload",
										filePath: videoRes.tempFilePath,
										name: 'file',
										header: {
											'Authorization': ('Bearer ' + loginInfo.token) ||
												''
										},
										formData: {
											'fileType': 'CheckVideo'
										},
										success: (uploadFileRes) => {
											uni.hideLoading();
											let res = JSON.parse(uploadFileRes.data);
											let filePath = res.data[0].filePath;
											let newFilePath = filePath.replace(/\\/g, "/");
											let d = {
												id: "0",
												checkDetailId: "0",
												imgName: `${getApp().globalData.websiteUrl}${newFilePath}/${res.data[0].fileName}`,
												cover: img,
												width: videoW,
												height: videoH,
												softDelete: false
											}
											that.videos.push(d);
										}
									});
								})

								that.isAddVideoShow = false;
							} else {
								uni.hideLoading();
							}
						}

					}
				})
			},
			// 删除视频
			DelVideo(index) {
				this.delImgs.push(this.videos[index]);
				this.videos.splice(index, 1);
				this.isAddVideoShow = true;
			},
			// 播放视频
			playVideo(item) {
				wx.previewMedia({
					sources: [{
						url: item.imgName,
						type: "video",
						poster: item.imgSrc
					}]
				})
			},
			handleSubmit() {
				this.submitBtnState = false;
				let {
					doWorkInfo,
					imgs,
					videos,
					isCompleted,
					shopId,
					remark
				} = this;
				let newMediaFiles = JSON.parse(JSON.stringify(imgs));
				if (videos.length > 0) {
					if (videos[0].checkDetailId) {
						newMediaFiles.push({
							"checkDetailId": videos[0].checkDetailId,
							"id": videos[0].id,
							"imgName": videos[0].imgName,
							"cover": videos[0].cover,
							"width": videos[0].width,
							"height": videos[0].height,
							"softDelete": false
						})
					} else {
						newMediaFiles.push({
							"id": "0",
							"checkDetailId": "0",
							"imgName": videos[0].imgName,
							"cover": videos[0].cover,
							"width": videos[0].width,
							"height": videos[0].height,
							"softDelete": false
						})
					}
				}
				if (isCompleted == -1) {
					getApp().showToast("请勾选完成状态");
				} else if (isCompleted == 1 && imgs.length == 0 && videos.length == 0) {
					getApp().showToast("请上传点检痕迹");
				} else {
					getApp().showLoading();
					let rqs = {
						"id": doWorkInfo.id,
						"checkId": doWorkInfo.checkId,
						"tempId": doWorkInfo.tempId,
						"class": doWorkInfo.class,
						"items": doWorkInfo.items,
						"standard": doWorkInfo.standard,
						"createTime": doWorkInfo.createTime,
						"imgNum": doWorkInfo.imgNum,
						"result": isCompleted,
						"frequency": doWorkInfo.frequency,
						"checkObject": doWorkInfo.checkObject,
						"checkPost": doWorkInfo.checkPost,
						"isTemp": "0",
						"shopId": shopId,
						"createUser": "0",
						"softDelete": false,
						"imgs": newMediaFiles,
						"totalCount": 0,
						"remark": isCompleted == 0 ? remark : "",
					};
					console.log('rqs', rqs);
					let delImgs = this.delImgs;
					if (delImgs.length > 0) {
						let p1 = new Promise((resolve) => {
							let rqsNum = 0;
							for (let i = 0; i < delImgs.length; i++) {
								apiRqs._deleteCompletedImage(delImgs[i].id).then((res) => {
									console.log('res', res);
									rqsNum++;
									if (res.code == 200) {
										console.log('删除成功');
									} else {
										getApp().showToast(res.msg);
									}

									if (rqsNum == delImgs.length) {
										resolve();
									}
								}).catch((err) => {
									console.log('err', err);
								})
							}

						})
						p1.then(() => {
							apiRqs._editCompletedWork(rqs).then((res) => {
								uni.hideLoading();
								if (res.code == 200) {
									getApp().showToast("修改成功", "success");
									setTimeout(() => {
										uni.navigateBack();
									}, 1500)
								} else {
									getApp().showToast(res.msg);
								}
							}).catch((err) => {
								console.log('err', err);
							})
						})
					} else {
						apiRqs._editCompletedWork(rqs).then((res) => {
							uni.hideLoading();
							if (res.code == 200) {
								getApp().showToast("修改成功", "success");
								setTimeout(() => {
									uni.navigateBack();
								}, 1500)
							} else {
								getApp().showToast(res.msg);
							}
						}).catch((err) => {
							console.log('err', err);
						})
					}


				}

			},
		},
	}
</script>

<style lang="less">
	page {
		background-color: #f5f5f5;
	}

	.workbench-detail {
		.detail-title {
			background-color: #fff;
			padding: 16px 17px;
			font-size: 16px;
			color: #000;
		}

		.detail-content {
			margin-top: 10px;

			.van-cell {
				padding-top: 16px;
				padding-bottom: 16px;
			}

			.van-icon {
				color: #008aff;
			}
		}

		.detail-tally-trace {
			margin-top: 10px;

			.detail-trace-title {
				font-size: 12px;
				color: #999999;
				margin-left: 16px;
			}

			.detail-tally-imgs {
				background-color: #fff;
				margin-top: 10px;
				padding: 0px 15px 15px 15px;
				box-sizing: border-box;
				display: flex;
				flex-wrap: wrap;

				.grid-item-box {
					width: 100px;
					height: 100px;
					position: relative;
					margin-left: 15px;
					margin-top: 15px;

					&:nth-child(3n+1) {
						margin-left: 0;
					}

					.tally-img {
						width: 100%;
						height: 100%;
					}

					.play-icon-bg {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						background-color: rgba(0, 0, 0, 0.3);
						z-index: 20;

						.play-icon {
							position: absolute;
							top: 50%;
							left: 50%;
							font-size: 30px;
							color: #fff;
							margin-left: -15px;
							margin-top: -15px;
						}
					}

					.delete-icon {
						position: absolute;
						top: -10px;
						right: -10px;
						color: #FF1010;
						background-color: #fff;
						font-size: 22px;
						border-radius: 50%;
						z-index: 99;
					}

					&.detail-tally-img-add {
						text-align: center;
						line-height: 100px;
						border: 1px solid #efefef;
						box-sizing: border-box;

						.add-icon {
							font-size: 28px;
							color: #999999;
						}
					}
				}
			}

			.detail-remark {
				margin-top: 10px;
				background-color: #fff;
				padding: 10px 16px;
				box-sizing: border-box;

				// &.isNotHistory {}

				&.isHistoryRemark {
					.uni-easyinput {
						.uni-easyinput__content {
							background-color: #fff !important;
							border: none !important;
							color: #999;

							.uni-easyinput__content-textarea {
								font-size: 12px !important;

							}
						}
					}
				}

			}
		}

		.detail-iscompleted {
			background-color: #fff;

			.detail-completed-form {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 16px 0px 16px 17px;

				.detail-completed-title {
					display: flex;
					align-items: center;

					.passed-icon {
						font-size: 16px;
						color: #008aff;
					}

					.completed-title-text {
						font-size: 14px;
						color: #333;
						margin-left: 5px;
					}
				}

				.detail-completed-radio-group {}
			}
		}

		.submit-btn {
			margin: 20px 15px;
			border: none;
			background-color: #008aff;
			color: #fff;
			font-size: 15px;
			height: 35pt;
			line-height: 35pt;

			&:active {
				background-color: #0076DB;
			}
		}

		.unsubmit-btn {
			margin: 20px 15px;
			border: none;
			background-color: #ccc;
			color: #fff;
			font-size: 15px;
			height: 35pt;
			line-height: 35pt;

			&::after {
				border: none;
			}
		}

		.box-height {
			height: 40px;
		}
	}
</style>
